import AMapLoader from '@amap/amap-jsapi-loader';

export function useAMap(elementId, proxy) {
    var map, mapObj
    var lastMarker
    window._AMapSecurityConfig = {
        securityJsCode: "c32a1b9a676690814bc26be0456f2eb7"
    };
    async function initMap(lng = '', lat = '', address = '') {
        return new Promise(resolve => {
            if (map) {
                if (lng != '') {
                    let item = {
                        lng: lng,
                        lat: lat,
                        address: address,
                    }
                    addMarker(item)
                }
                resolve()
            }
            AMapLoader.load({
                key: '4f77a5b362389d98e9f9deebb175aaa9',  //设置您的key
                version: "2.0",
                plugins: ['AMap.ToolBar', 'AMap.Driving', 'AMap.'],
                AMapUI: {
                    version: "1.1",
                    plugins: [],

                },
                Loca: {
                    version: "2.0.0"
                },
            }).then((AMap) => {
                map = new AMap.Map(elementId);
                mapObj = AMap
                if (lng != '') {
                    let item = {
                        lng: lng,
                        lat: lat,
                        address: address,
                    }
                    addMarker(item)
                }
                // let positionArr = [
                //   [113.357224, 34.977186],
                //   [114.555528, 37.727903],
                //   [112.106257, 36.962733],
                //   [109.830097, 31.859027],
                //   [116.449181, 39.98614],
                // ];
                // for (let item of positionArr) {
                //   let marker = new AMap.Marker({
                //     position: [item[0], item[1]],
                //   });
                //   this.map.add(marker);
                // }
                resolve(AMap)
            }).catch(e => {
                console.log(e);
            })
        })
    }
    function mapSearch(keyword, cb) {
        mapObj.plugin('AMap.AutoComplete', function () {
            var autoOptions = {
                //city 限定城市，默认全国
                city: '全国'
            };
            // 实例化AutoComplete
            var autoComplete = new mapObj.AutoComplete(autoOptions);
            // 根据关键字进行搜索
            autoComplete.search(keyword, function (status, result) {
                // 搜索成功时，result即是对应的匹配数据
                if (result && result.tips) {
                    let arr = []
                    result.tips.forEach(element => {
                        arr.push({
                            value: element.name + '(' + element.address + ')',
                            link: JSON.parse(JSON.stringify(element)),
                        })
                    });
                    cb(arr)
                }

            })
        })
    }

    function addMarker(item) {
        var marker = new mapObj.Marker({
            position: new mapObj.LngLat(item.lng, item.lat),   // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
            title: item.address
        });
        if (lastMarker) {
            map.remove(lastMarker)
        }
        map.add(marker)
        map.setFitView();
        // marker.on('click', proxy.handleMarkerClick(row))
        lastMarker = marker
    }

    function createMarkers(item) {
        if (item.lng == '' || item.lat == '') {
            return
        }
        var icon = new mapObj.Icon({
            size: new mapObj.Size(32, 32),
            image: getIconUrl(item.alarm_status),
            imageSize: new mapObj.Size(32, 32)
        });

        var marker = new mapObj.Marker({
            position: new mapObj.LngLat(item.lng, item.lat),   // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
            title: item.address,
            icon: icon,
            offset: [-16, -32]
        });
        marker.on('click', () => {
            proxy.handleMarkerClick(item)
        })
        if (!window.markerMap) {
            window.globalMarkers = []
            window.markerMap = []
            window.markerInfo = []
        }
        window.markerMap[item.sn] = marker
        window.markerInfo[item.sn] = item
        window.globalMarkers.push(marker)
    }

    function addMarkersToMap() {
        if (!window.globalMarkers) {
            return
        }
        map.add(window.globalMarkers)
        map.setCenter(window.globalMarkers[0].getPosition())
    }

    function setMapCenter(item, zoom = 0) {
        if (item.lng == '' || item.lat == '') {
            return
        }
        if (zoom > 0) {
            map.setZoom(zoom);
        }
        map.setCenter([item.lng, item.lat])
    }

    function changeMarkerStatus(item) {
        if (window.markerMap[item.sn]) {
            window.markerMap[item.sn].setIcon(new mapObj.Icon({
                size: new mapObj.Size(32, 32),
                image: getIconUrl(item.alarm_status),
                imageSize: new mapObj.Size(32, 32)
            }))
            // map.setCenter(window.markerMap[item.sn].getPosition())
        }
    }

    function getIconUrl(alarmStatus = 0) {
        let iconUrl = 'https://qiniu.change90.com/icon/normal.png'
        if (alarmStatus) {
            switch (alarmStatus) {
                case 0:
                    iconUrl = 'https://qiniu.change90.com/icon/normal.png'
                    break
                case 1:
                    iconUrl = 'https://qiniu.change90.com/icon/warning.png'
                    break
                case 2:
                    iconUrl = 'https://qiniu.change90.com/icon/fault.png'
                    break
            }
        }
        return iconUrl
    }

    function alertInfoWindow(item, dom) {
        if (!window.markerMap[item.sn]) {
            return
        }
        var infoWindow = new mapObj.InfoWindow({
            isCustom: true,  //使用自定义窗体
            content: dom,
            autoMove: true,
            // offset: new mapObj.Pixel(-10, -50)
            offset: new mapObj.Pixel(-150, -230)
        });
        infoWindow.open(map, window.markerMap[item.sn].getPosition());
        // 解决2.0版本无法滚动问题
        infoWindow.on('mouseover', () => map.setStatus({ scrollWheel: false }))
        infoWindow.on('mouseout', () => {
            map.setStatus({ scrollWheel: true })
        })

        proxy.showDiv = true
    }



    function closeInfoWindow() {
        proxy.showDiv = false
        map.clearInfoWindow();
    }
    return {
        initMap,
        mapSearch,
        addMarker,
        createMarkers,
        addMarkersToMap,
        setMapCenter,
        changeMarkerStatus,
        alertInfoWindow,
        closeInfoWindow
    }
}